local zaiqi = fk.CreateSkill {

  name = "joyex__zaiqi",

  tags = {  },

}



zaiqi:addEffect(fk.EventPhaseStart, {
  name = "joyex__zaiqi",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(zaiqi.name) then
      if player.phase == Player.Draw and player:isWounded() then
        return true
      elseif player.phase == Player.Finish  then
        local room = player.room
        local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
        if turn_event == nil then return false end
        local n = 0
        player.room.logic:getActualDamageEvents( 1, function(e)
            local damage = e.data[1]
            if damage.from == player then
                n = n + damage.damage
            end
        end, nil, turn_event.id)
        if n > 0 then
            event:setCostData(self, n)
            return true
        end
      end
    end 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = player.phase == Player.Draw and player:getLostHp() or event:getCostData(self)
    local cards = room:getNCards(n)
    room:moveCards{
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = zaiqi.name,
      proposer = player.id,
    }
    room:delay(2000)
    local hearts, to_get = {}, {}
    for _, id in ipairs(cards) do
      if Fk:getCardById(id).suit == Card.Heart then
        table.insert(hearts, id)
      else
        table.insert(to_get, id)
      end
    end
    if #hearts > 0 then
      if player:isWounded() then
        room:recover({
          who = player,
          num = math.min(#hearts, player:getLostHp()),
          recoverBy = player,
          skillName = zaiqi.name,
        })
      end
      room:moveCards{
        ids = hearts,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonPutIntoDiscardPile,
        skillName = zaiqi.name,
      }
    end
    if #to_get > 0 and not player.dead then
      room:obtainCard(player, to_get, true, fk.ReasonJustMove)
    end
    cards = table.filter(cards, function (id)
      return room:getCardArea(id) == Card.Processing
    end)
    if #cards > 0 then
      room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonJustMove, zaiqi.name)
    end
    if player.phase == Player.Draw then
      return true
    end
  end,
})

return zaiqi